import { defineStore } from "pinia";

interface IUserData {
  token?: string;
  userid?: string;
}
interface ICarItem {
  proid: string;
  checked: boolean;
  img: string;
  proname: string;
  originprice: number;
  goodsNum: number;
}

// 规范：单词以use开头的驼峰命名，最好结尾用store这个单词
// 第一个参数是store的名字，第二个参数和之前学习vuex的时候一样的配置项
export const useUserInfoStore = defineStore("userInfo", {
  // state和actions以及getters里面的变量取名不能相同
  state: () => {
    return {
      userData: {},
      goodsList: [],
      userToken: "",
      userId: "",
    };
  },
  actions: {
    setUserToken(payload: string) {
      this.userToken = payload;
    },
    setUserId(payload: string) {
      this.userId = payload;
    },
    setUserData(palyload: IUserData) {
      this.userData = palyload;
    },
    setGoodsList(palyload: ICarItem) {
      // 假设goodsList里什么都没有，那么就直接把传过来的数据push进去
      if (this.goodsList.length === 0) {
        (this.goodsList as ICarItem[]).push(palyload);
      } else {
        // 假设现在goodsList里有数据，那么据需要判断：
        // 当前已有的数据是否和新加入进来的数据是同一条
        const tmp = (this.goodsList as ICarItem[]).find((v) => {
          return v.proid === palyload.proid;
        });
        if (tmp) {
          // 假设新加入的数据和已有数据是同一条，那么直接变更已有数据的数量即可
          tmp.goodsNum++;
        } else {
          // 假设新加入的数据和已有数据不是同一条，那么直接把新数据push进去
          (this.goodsList as ICarItem[]).push(palyload);
        }
      }
    },
    setGoodsListItem(palyload: string) {
      const index = (this.goodsList as ICarItem[]).findIndex((v) => {
        return v.proid === palyload;
      });
      this.goodsList.splice(index, 1);
    },
  },
  getters: {
    getUserData(): IUserData {
      return this.userData;
    },
    getGoodsList(): ICarItem[] {
      return this.goodsList;
    },
    getUserToken(): string {
      return this.userToken;
    },
  },
});
